package com.happy.mycar;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.ServiceCompat;

public class MyBLEService extends Service {

    @SuppressLint("ForegroundServiceType")
    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel(getApplication());
        CBLEDevice.getInstance().setContext(this);
        // 启动前台服务
        int type = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            type = ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE;
        }
        ServiceCompat.startForeground(
                /* service = */ this,
                /* id = */ 1, // Cannot be 0
                /* notification = */ createNotification("后台服务运行中...").build(),
                /* foregroundServiceType = */ type
        );
        //startForeground(1, createNotification("后台运行中...").build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 在这里实现你的后台任务逻辑
        new Thread(() -> {
            CBLEDevice BLEDev= CBLEDevice.getInstance();

            BLEDev.registerReceiver();
            BLEDev.LoadConfig(getApplicationContext().getSharedPreferences("MyCar", Context.MODE_PRIVATE));
            AccelerometerSensor accelerometerSensor = new AccelerometerSensor(getApplicationContext());
            //上次扫描时间
            long lastScanTime = 0;
            boolean canScanBLE = true;
            while (true) {
                try {
                    //判断是否有运动
                    canScanBLE=accelerometerSensor.IsMoving();

                    if (BLEDev.isConnected()) {
                        System.out.println("蓝牙已连接...");
                        Thread.sleep(1000);
                    } else if(canScanBLE){
                        long scanTimeDef = System.currentTimeMillis() - lastScanTime;
                        if(scanTimeDef > 6000) {
                            //6秒内未扫描过
                            lastScanTime = System.currentTimeMillis();
                            //开始扫描
                            System.out.println("开始扫描...");
                            BLEDev.connectToBLEDevice("MyCar");
                        }
                        else {
                            Thread.sleep(6000-scanTimeDef);
                        }
                    }
                    else {
                        //蓝牙未连接，且未运动就延时一秒再处理...
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
            BLEDev.unregisterReceiver();
            stopSelf();
        }).start();
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // 前台服务不需要绑定，返回 null
        return null;
    }

    static void createNotificationChannel(Context ctx) {
        NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
        if (notificationManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channelCreate = notificationManager.getNotificationChannel("channel_id");
            if(channelCreate==null) {
                NotificationChannel channel = new NotificationChannel(
                        "channel_id",
                        "MyCar",
                        NotificationManager.IMPORTANCE_DEFAULT
                );
                channel.setName("智能车钥匙服务通知");
                channel.setSound(null,null);
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartServiceIntent = new Intent(getApplicationContext(), MyBLEService.class);
        restartServiceIntent.setPackage(getPackageName());
        startService(restartServiceIntent);
        super.onTaskRemoved(rootIntent);
    }

    private NotificationCompat.Builder createNotification(String content) {
        Intent intent = new Intent(this, MainActivity.class);
        // 如果希望在应用已在后台运行时，将其带到前台并清除之前的活动栈，可以添加以下标志
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 创建通知
        return new NotificationCompat.Builder(this, "channel_id")
                .setContentTitle("智能车钥匙")
                .setContentText(content)
                .setOnlyAlertOnce(true)
                //防止通知被关闭
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH);
    }
}